package com.dongdongshop.shiro;

import com.dongdongshop.pojo.Admin;
import com.dongdongshop.service.LoginService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;

//继承抽象类 实现抽象方法
public class LoginRealm extends AuthorizingRealm {

    @DubboReference
    private LoginService loginService;

    @Override//授权方法
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权");
        //当访问呢到需要授权的页面时 在此进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<String> perms = new ArrayList<>();
        perms.add("crud_delete");
        perms.add("crud_update");
        info.addStringPermissions(perms);
        return info;
    }

    @Override//认证方法(登录方法)
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入登录");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String name = token.getUsername();
        Admin admin = loginService.selectByName(name);
        if (admin == null) {
            return null;
        }
       //1.表示登录成功后的对象 2.数据库中的密码 3盐 4.用户的真实名字
        return new SimpleAuthenticationInfo(admin,admin.getPassword(),ByteSource.Util.bytes(admin.getSalt()), admin.getName());
    }
}
